package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.service.IAiImageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * AI图片生成服务实现类
 */
@Service
public class AiImageServiceImpl implements IAiImageService {

    @Value("${ai.api.key}")
    private String apiKey;

    @Value("${ai.api.url}")
    private String apiUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 根据提示词生成图片
     *
     * @param prompt 提示词
     * @return 生成的图片URL
     */
    @Override
    public String generateImage(String prompt) {
        try {
            // 调用AI API生成图片
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("prompt", prompt);
            requestBody.put("n", 1);
            requestBody.put("size", "1024x1024");

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            Map<String, Object> response = restTemplate.postForObject(apiUrl, request, Map.class);

            // 获取生成的图片数据
            String imageData = ((Map<String, Object>) ((java.util.List<?>) response.get("data")).get(0)).get("b64_json").toString();
            byte[] imageBytes = Base64.getDecoder().decode(imageData);

            // 将图片保存到服务器
            MultipartFile multipartFile = new Base64MultipartFile(imageBytes, "image.png", "image/png");
            String fileName = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), multipartFile);

            // 返回访问URL
            return RuoYiConfig.getProfile() + fileName;
        } catch (Exception e) {
            throw new RuntimeException("AI图片生成失败", e);
        }
    }

    /**
     * 用于处理Base64图片数据的MultipartFile实现
     */
    private static class Base64MultipartFile implements MultipartFile {
        private final byte[] content;
        private final String filename;
        private final String contentType;

        public Base64MultipartFile(byte[] content, String filename, String contentType) {
            this.content = content;
            this.filename = filename;
            this.contentType = contentType;
        }

        @Override
        public String getName() {
            return filename;
        }

        @Override
        public String getOriginalFilename() {
            return filename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() {
            return content;
        }

        @Override
        public java.io.InputStream getInputStream() {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(java.io.File dest) throws IllegalStateException, java.io.IOException {
            java.nio.file.Files.write(dest.toPath(), content);
        }
    }
} 